package com.wzb.mybatisplus.bitaction.electrumaction.one;

import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.DumpedPrivateKey;
import org.bitcoinj.core.LegacyAddress;
import org.bitcoinj.core.SegwitAddress;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.bouncycastle.util.encoders.Hex;

import java.math.BigInteger;
import java.security.SecureRandom;

public class BitcoinKeyConverter {

    // 从WIF格式私钥生成公钥和地址
    public static KeyPair generateFromWIF(String wifPrivateKey) {
        try {
            NetworkParameters params = MainNetParams.get();
            DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(params, wifPrivateKey);
            ECKey ecKey = dumpedPrivateKey.getKey();

            return extractKeyInfo(ecKey, params);

        } catch (Exception e) {
            throw new RuntimeException("无效的WIF私钥: " + e.getMessage());
        }
    }

    // 从十六进制私钥生成公钥和地址
    public static KeyPair generateFromHex(String hexPrivateKey) {
        try {
            NetworkParameters params = MainNetParams.get();
            byte[] privKeyBytes = Hex.decode(hexPrivateKey);
            ECKey ecKey = ECKey.fromPrivate(privKeyBytes);

            return extractKeyInfo(ecKey, params);

        } catch (Exception e) {
            throw new RuntimeException("无效的十六进制私钥: " + e.getMessage());
        }
    }

    // 生成新的随机私钥-公钥对
    public static KeyPair generateNewKeyPair() {
        NetworkParameters params = MainNetParams.get();
        ECKey ecKey = new ECKey(); // 随机生成新密钥

        return extractKeyInfo(ecKey, params);
    }

    // 提取密钥信息
    private static KeyPair extractKeyInfo(ECKey ecKey, NetworkParameters params) {
        KeyPair keyPair = new KeyPair();

        // 私钥信息
        keyPair.setPrivateKeyHex(Hex.toHexString(ecKey.getPrivKeyBytes()));
        keyPair.setPrivateKeyWIF(ecKey.getPrivateKeyAsWiF(params));

        // 公钥信息
        keyPair.setPublicKeyCompressed(Hex.toHexString(ecKey.getPubKey()));
        keyPair.setPublicKeyUncompressed(Hex.toHexString(ecKey.getPubKeyPoint().getEncoded(false)));

        // 地址信息
        keyPair.setLegacyAddress(LegacyAddress.fromKey(params, ecKey).toString());
        keyPair.setSegwitAddress(SegwitAddress.fromKey(params, ecKey).toString());

        // P2SH-P2WPKH 嵌套隔离见证地址
        keyPair.setP2shSegwitAddress(LegacyAddress.fromKey(params, ecKey).toString());

        return keyPair;
    }

    // BIP32 HD钱包派生
    public static KeyPair generateFromSeed(byte[] seed) {
        NetworkParameters params = MainNetParams.get();

        // 从种子生成主密钥
        DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(seed);

        // BIP44路径: m/44'/0'/0'/0/0
        DeterministicKey purpose = HDKeyDerivation.deriveChildKey(masterKey, 44 | 0x80000000);
        DeterministicKey coinType = HDKeyDerivation.deriveChildKey(purpose, 0 | 0x80000000);
        DeterministicKey account = HDKeyDerivation.deriveChildKey(coinType, 0 | 0x80000000);
        DeterministicKey change = HDKeyDerivation.deriveChildKey(account, 0);
        DeterministicKey addressKey = HDKeyDerivation.deriveChildKey(change, 0);

        // 转换为ECKey
        ECKey ecKey = ECKey.fromPrivate(addressKey.getPrivKeyBytes());

        return extractKeyInfo(ecKey, params);
    }

    public static void main(String[] args) {
//        BigInteger c = new BigInteger("55066263022277343669578718895168534326250603453777594175500187360389116729240");
//        System.out.println(new BigInteger("55066263022277343669578718895168534326250603453777594175500187360389116729240"));
//        System.out.println(c.multiply(BigInteger.valueOf(8)).mod(new BigInteger("115792089237316195423570985008687907852837564279074904382605163141518161494337")));
        // 示例1: 生成新的密钥对
//        System.out.println("1. 生成新的随机密钥对:");
//        KeyPair newKeyPair = BitcoinKeyConverter.generateNewKeyPair();
//        System.out.println(newKeyPair);

        System.out.println("2. 从WIF私钥转换:");
        String wifPrivateKey = "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAvUcVfH";
        try {
            KeyPair wifKeyPair = BitcoinKeyConverter.generateFromWIF(wifPrivateKey);
            String address = wifKeyPair.getLegacyAddress(); // 比特币创始区块地址公钥地址
            String publicKey = wifKeyPair.getPublicKeyCompressed();
            publicKey = publicKey.substring(2);
            System.out.println("公钥："+ new BigInteger(publicKey,16));
            System.out.println(wifKeyPair);
        } catch (Exception e) {
            System.out.println("WIF私钥转换失败: " + e.getMessage());
        }
    }
}
